package com.dwy2002.user.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dwy2002.common.Result;
import com.dwy2002.common.exception.EmptyIdException;
import com.dwy2002.common.utils.Validator;
import com.dwy2002.enums.Status;
import com.dwy2002.pojo.dto.users.UsersPageDTO;
import com.dwy2002.pojo.po.users.Users;
import com.dwy2002.pojo.vo.users.UserinfoVO;
import com.dwy2002.user.mapper.UsersMapper;
import com.dwy2002.user.service.IRoleService;
import com.dwy2002.user.service.IUserManagerService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

import static com.dwy2002.common.Result.*;
import static com.dwy2002.common.utils.Utils.*;
import static com.dwy2002.enums.rabbit.ReviewsRabbitConstants.REVIEWS_REQUEST_QUEUE;

/**
 * @author 杜伟毅
 * @version 1.0
 * @since 2025/03/16
 */
@Service
@RequiredArgsConstructor
public class UserManagerServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUserManagerService {
    private final RabbitTemplate rabbitTemplate;
    private final IRoleService roleService;

    /**
     * 用户分页查询分页
     *
     * @param dto 用户分页DTO
     * @author 杜伟毅
     * @since 2025/3/16 0016 15:11
     */
    @Override
    public Result<Page<Users>> getUsersPage(UsersPageDTO dto) {
        Validator.of(dto)
                .mustSatisfy(isPageNull(dto.getPageNo(), dto.getPageSize()), "请传入分页数据")
                .mustSatisfy(isPageZero(dto.getPageNo(), dto.getPageSize()), "分页数据不能为0")
                .validate();

        //分页
        Page<Users> page = new Page<>(dto.getPageNo(), dto.getPageSize());
        return success(this.baseMapper.selectUserPage(page, dto));
    }


    /**
     * 批量查询关联用户
     *
     * @param ids 用户id集合
     * @author 杜伟毅
     * @since 2025/3/24 0024 20:47
     */
    @Override
    public List<Users> getUserBatchByIds(Set<String> ids) {
        if (ids == null || ids.isEmpty()) throw new EmptyIdException("getUserBatchByIds");
        LambdaQueryWrapper<Users> lqw = new LambdaQueryWrapper<>();
        lqw.in(Users::getId, ids);
        return list(lqw);
    }

    /**
     * 将用户锁定
     *
     * @param id 用户id
     * @author 杜伟毅
     * @since 2025/5/11 0011 18:44
     */
    @Override
    public Result<Void> lockedUser(String id) {
        int i = 1;
        if (isEmptyOrNull(id)) return fail(Status.BAD_REQUEST, "id不能为空");
        LambdaUpdateWrapper<Users> luw = new LambdaUpdateWrapper<>();
        luw.eq(Users::getId, id)
                .set(Users::getIsLocked, i);
        boolean update = update(luw);
        return handleResult(update, "锁定成功", "锁定失败");
    }

    /**
     * 将用户解锁
     *
     * @param id 用户id
     * @author 杜伟毅
     * @since 2025/5/11 0011 18:44
     */
    @Override
    public Result<Void> unlockUser(String id) {
        int i = 0;
        if (isEmptyOrNull(id)) return fail(Status.BAD_REQUEST, "id不能为空");
        LambdaUpdateWrapper<Users> luw = new LambdaUpdateWrapper<>();
        luw.eq(Users::getId, id)
                .set(Users::getIsLocked, i);
        boolean update = update(luw);
        return handleResult(update, "解锁成功", "解锁失败");
    }

    /**
     * 获取用户个人信息
     *
     * @param id 用户id
     * @author 杜伟毅
     * @since 2025/5/11 0011 23:58
     */
    @Override
    public Result<UserinfoVO> getUserinfo(String id) {
        if (isEmptyOrNull(id)) return fail(Status.BAD_REQUEST, "id不能为空");
        Users user = getById(id);
        if (ObjectUtils.isEmpty(user)) return fail(Status.BAD_REQUEST, "用户不存在");
        UserinfoVO userinfoVO = BeanUtil.copyProperties(user, UserinfoVO.class);
        userinfoVO.setRoleName(roleService.getUserRole(id).getRoleName());
        return success(userinfoVO);
    }

    //---------------------------------------------------------------------------------------

    /**
     * @author 杜伟毅
     * @since 2025/3/24 0024 21:10
     */
    @RabbitListener(queues = REVIEWS_REQUEST_QUEUE)
    public void handleReviewsRequest(Set<String> userIds, Message message) {
        List<Users> usersList = getUserBatchByIds(userIds);

        // 发送响应到ReplyTo队列
        rabbitTemplate.convertAndSend(
                message.getMessageProperties().getReplyTo(),
                usersList,
                msg -> {
                    msg.getMessageProperties().setCorrelationId(message.getMessageProperties().getCorrelationId());
                    return msg;
                }
        );
    }

}
